package com.lanou.dllo.vc.activity;

import android.content.Intent;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.Chronometer;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMCallStateChangeListener;
import com.easemob.chat.EMChatManager;
import com.easemob.exceptions.EMServiceNotReadyException;
import com.lanou.dllo.vc.R;

import java.util.UUID;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by dllo on 15/12/2.
 */
public class VoiceCallActivity extends BaseActivity{


    private boolean isInComingCall;
    private SoundPool soundPool;
    private int outgoing;
    private String st1;
    private Handler handler = new Handler();
    private int streamID;
    protected AudioManager audioManager;
    protected Ringtone ringtone;
    private boolean isHandsfreeState;

    @Bind(R.id.calledName)
    TextView calledName;
    @Bind(R.id.titleTv)
    TextView titleTv;

    private String username,msgid;
    private EMCallStateChangeListener callStateListener;

    @Override
    protected int getLayout() {
        return R.layout.activity_voice_call;
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);

//        Intent intent = getIntent();
//        if (intent!=null) {
//            username = intent.getStringExtra("username");
//        }
//        calledName.setText(username);
//
//        // 注册语音电话的状态的监听
//        addCallStateListener();
//        msgid = UUID.randomUUID().toString();

        // 注册语音电话的状态的监听
        addCallStateListener();
        msgid = UUID.randomUUID().toString();

        username = getIntent().getStringExtra("username");
        // 语音电话是否为接收的
        isInComingCall = getIntent().getBooleanExtra("isComingCall", false);

        // 设置通话人
        calledName.setText(username);
        if (!isInComingCall) {// 拨打电话
            soundPool = new SoundPool(1, AudioManager.STREAM_RING, 0);
            outgoing = soundPool.load(this, R.raw.em_outgoing, 1);

            st1 = getResources().getString(R.string.Are_connected_to_each_other);
            titleTv.setText(st1);
            handler.postDelayed(new Runnable() {
                public void run() {
                    streamID = playMakeCallSounds();
                }
            }, 300);
            try {
                // 拨打语音电话
                EMChatManager.getInstance().makeVoiceCall(username);
            } catch (EMServiceNotReadyException e) {
                e.printStackTrace();
                final String st2 = getResources().getString(R.string.Is_not_yet_connected_to_the_server);
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(VoiceCallActivity.this, st2, 0).show();
                    }
                });
            }
        } else { // 有电话进来
//            voiceContronlLayout.setVisibility(View.INVISIBLE);
            Uri ringUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
            audioManager.setMode(AudioManager.MODE_RINGTONE);
            audioManager.setSpeakerphoneOn(true);
            ringtone = RingtoneManager.getRingtone(this, ringUri);
            ringtone.play();
        }


    }


    /**
     * 设置电话监听
     */
    void addCallStateListener() {
        callStateListener = new EMCallStateChangeListener() {

            @Override
            public void onCallStateChanged(CallState callState, CallError error) {
                // Message msg = handler.obtainMessage();
                switch (callState) {

                    case CONNECTING: // 正在连接对方
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                // TODO Auto-generated method stub
                                titleTv.setText(st1);
                            }

                        });
                        break;
                    case CONNECTED: // 双方已经建立连接
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                // TODO Auto-generated method stub
                                String st3 = getResources().getString(R.string.have_connected_with);
                                titleTv.setText(st3);
                            }

                        });
                        break;

                    case ACCEPTED: // 电话接通成功
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                try {
                                    if (soundPool != null)
                                        soundPool.stop(streamID);
                                } catch (Exception e) {
                                }
                                if(!isHandsfreeState)
                                    closeSpeakerOn();
                                //显示是否为直连，方便测试
//                                ((TextView)findViewById(R.id.tv_is_p2p)).setText(EMChatManager.getInstance().isDirectCall()
//                                        ? R.string.direct_call : R.string.relay_call);
//                                chronometer.setVisibility(View.VISIBLE);
//                                chronometer.setBase(SystemClock.elapsedRealtime());
                                // 开始记时
//                                chronometer.start();
                                String str4 = getResources().getString(R.string.In_the_call);
                                titleTv.setText(str4);
//                                callingState = CallingState.NORMAL;
                            }

                        });
                        break;
                    case DISCONNNECTED: // 电话断了
                        final CallError fError = error;
                        runOnUiThread(new Runnable() {
                            private void postDelayedCloseMsg() {
                                handler.postDelayed(new Runnable() {

                                    @Override
                                    public void run() {
//                                        saveCallRecord(0);
                                        Animation animation = new AlphaAnimation(1.0f, 0.0f);
                                        animation.setDuration(800);
//                                        findViewById(R.id.root_layout).startAnimation(animation);
                                        finish();
                                    }

                                }, 200);
                            }

                            @Override
                            public void run() {
//                                chronometer.stop();
//                                callDruationText = chronometer.getText().toString();
//                                String st2 = getResources().getString(R.string.The_other_party_refused_to_accept);
//                                String st3 = getResources().getString(R.string.Connection_failure);
//                                String st4 = getResources().getString(R.string.The_other_party_is_not_online);
//                                String st5 = getResources().getString(R.string.The_other_is_on_the_phone_please);
//
//                                String st6 = getResources().getString(R.string.The_other_party_did_not_answer_new);
//                                String st7 = getResources().getString(R.string.hang_up);
//                                String st8 = getResources().getString(R.string.The_other_is_hang_up);
//
//                                String st9 = getResources().getString(R.string.did_not_answer);
//                                String st10 = getResources().getString(R.string.Has_been_cancelled);
//                                String st11 = getResources().getString(R.string.hang_up);

//                                if (fError == CallError.REJECTED) {
//                                    callingState = CallingState.BEREFUESD;
//                                    callStateTextView.setText(st2);
//                                } else if (fError == CallError.ERROR_TRANSPORT) {
//                                    callStateTextView.setText(st3);
//                                } else if (fError == CallError.ERROR_INAVAILABLE) {
//                                    callingState = CallingState.OFFLINE;
//                                    callStateTextView.setText(st4);
//                                } else if (fError == CallError.ERROR_BUSY) {
//                                    callingState = CallingState.BUSY;
//                                    callStateTextView.setText(st5);
//                                } else if (fError == CallError.ERROR_NORESPONSE) {
//                                    callingState = CallingState.NORESPONSE;
//                                    callStateTextView.setText(st6);
//                                } else {
//                                    if (isAnswered) {
//                                        callingState = CallingState.NORMAL;
//                                        if (endCallTriggerByMe) {
////                                        callStateTextView.setText(st7);
//                                        } else {
//                                            callStateTextView.setText(st8);
//                                        }
//                                    } else {
//                                        if (isInComingCall) {
//                                            callingState = CallingState.UNANSWERED;
//                                            callStateTextView.setText(st9);
//                                        } else {
//                                            if (callingState != CallingState.NORMAL) {
//                                                callingState = CallingState.CANCED;
//                                                callStateTextView.setText(st10);
//                                            }else {
//                                                callStateTextView.setText(st11);
//                                            }
//                                        }
//                                    }
//                                }
                                postDelayedCloseMsg();
                            }

                        });

                        break;

                    default:
                        break;
                }

            }
        };
        EMChatManager.getInstance().addCallStateChangeListener(callStateListener);
    }

    // 关闭扬声器
    protected void closeSpeakerOn() {

        try {
            if (audioManager != null) {
                // int curVolume =
                // audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
                if (audioManager.isSpeakerphoneOn())
                    audioManager.setSpeakerphoneOn(false);
                audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
                // audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
                // curVolume, AudioManager.STREAM_VOICE_CALL);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    /**
     * 播放拨号响铃
     *
     * @param sound
     * @param number
     */
    protected int playMakeCallSounds() {
        try {
            // 最大音量
            float audioMaxVolumn = audioManager.getStreamMaxVolume(AudioManager.STREAM_RING);
            // 当前音量
            float audioCurrentVolumn = audioManager.getStreamVolume(AudioManager.STREAM_RING);
            float volumnRatio = audioCurrentVolumn / audioMaxVolumn;

            audioManager.setMode(AudioManager.MODE_RINGTONE);
            audioManager.setSpeakerphoneOn(false);

            // 播放
            int id = soundPool.play(outgoing, // 声音资源
                    0.3f, // 左声道
                    0.3f, // 右声道
                    1, // 优先级，0最低
                    -1, // 循环次数，0是不循环，-1是永远循环
                    1); // 回放速度，0.5-2.0之间。1为正常速度
            return id;
        } catch (Exception e) {
            return -1;
        }
    }


    @Override
    protected void initData() {
        /**
         * 拨打语音通话
         * @param to
         * @throws EMServiceNotReadyException
         */
        try {
            EMChatManager.getInstance().makeVoiceCall(username);
        } catch (EMServiceNotReadyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


}
